package com.atguigu.gulimall.ssoserver.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token") String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }
    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String redirect_url, Model model,
                        @CookieValue(value = "sso_token",required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            //说明有登录过，浏览器留下痕迹，直接跳回去
            return "redirect:" + redirect_url + "?token=" + sso_token;
        }
        model.addAttribute("url", redirect_url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("url") String url,
                          HttpServletResponse response) {

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登陆成功就要跳转,跳回之前的页面；

            //把登陆成功的用户存起来
            String uuid = UUID.randomUUID().toString().replace("_", "");
            redisTemplate.opsForValue().set(uuid, username);
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:" + url + "?token=" + uuid;
        }

        //登陆失败
        return "login";


    }

}
